<template>
  <div class="header">
    <div class="logo">
      <img src="../assets/松树.svg" class="logo-img" @click="handleToHome">
      <p class="title" @click="handleToHome">树洞</p>
    </div>
    <div class="user" v-if="userStore.user.isLogin">
      <img :src="userStore.user.avatar" class="avatar" @click="$emit('clickUserInfo')">
    </div>
    <div class="login-signup" v-else>
      <el-button text bg @click="$emit('clickLogin')">登录</el-button>
      <el-button text bg @click="$emit('clickSignup')">注册</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted } from 'vue'
import { emitter } from './Wall.vue'
import { useUserStore } from '../store/user'

export default defineComponent({
  emits: ['clickLogin', 'clickSignup', 'clickUserInfo'],
  setup() {
    const userStore = useUserStore()
    const handleToHome = () => {
      emitter.emit('toHome')
    }
    // 组件挂载时，尝试通过 token 去请求用户信息，来达到刷新页面保持用户登录的效果
    onMounted(async () => {
      if (!userStore.user.isLogin) {
        await userStore.fetchCurrentUser()
      }
    })

    return { handleToHome, userStore }
  }
})
</script>

<style lang="less" scoped>
.header {
  width: 100%;
  height: 52px;
  background: rgba(255, 255, 255, 0.80);
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  box-sizing: border-box;
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
  z-index: 1;

  .logo {
    display: flex;
    align-items: center;
    width: 200px;

    .logo-img {
      height: 52px;
      cursor: pointer;
    }

    .title {
      margin-left: 10px;
      font-size: 20px;
      font-family: 'Times New Roman', Times, serif;
      font-weight: 700;
      cursor: pointer;
    }
  }

  .user {
    width: 200px;

    .avatar {
      float: right;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      cursor: pointer;
    }
  }
}
</style>